package com.xkdx.guangguang.fragment.my.setup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.my.setup.ExchangeListModule.MyExchange;
import com.xkdx.guangguang.fragment.user.UserRegistModule.DetailInfo;
import com.xkdx.guangguang.fragment.user.UserRegistModule.User;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.presistence.receive.ReceiveAction;
import com.xkdx.guangguang.presistence.receive.ReceiveModule;
import com.xkdx.guangguang.presistence.receive.ReceivePresistence;
import com.xkdx.guangguang.util.SharePrefenceUtil;
import com.xkdx.guangguang.zxing.ORFragment;

public class ExchangeListFragment extends BaseFragment {
	View view;
	User user;
	DetailInfo info;
	Button back;
	ListView hasExchangelistview, noExchangelistview, ls_not_pay;
	ScrollView exchange_success_sv;
	LinearLayout recevied_rl, unrecevied_rl, exhchange_pb_ll, ll_not_pay;
	String tipMessage;
	MyExchange exchange;
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;
	TextView exchange_recevied, exchange_unrecevied, tv_not_pay_num;
	public static List<MyExchange> hasExChangeList = new ArrayList<MyExchange>(),
			noExChangeList = new ArrayList<MyExchange>(),
			notPayList = new ArrayList<MyExchange>();
	SharePrefenceUtil su;
	ProgressDialog pd;
	ExChangeAdapter hasAdapter, noAdapter, notPayAdapter;
	// 获取兑换列表
	ExchangeListAction exchangeListAction;
	ExchangeListModule exchangeListModule;
	ExchangeListPresistence exchangeListPresistence;
	// 领取
	ReceiveAction receiveAction;
	ReceiveModule receiveModule;
	ReceivePresistence receivePresistence;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		pd = new ProgressDialog(getActivity());
		pd.setMessage("正在领取...");

		su = new SharePrefenceUtil(getActivity(), IConstants.SP_USER);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.empty_photo)
				.showImageForEmptyUri(R.drawable.empty_photo)
				.showImageOnFail(R.drawable.empty_photo)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.exchange, container, false);
		findView();
		setOnClick();
		showLoading();

		return view;
	}

	@Override
	public void findView() {

		back = (Button) view.findViewById(R.id.exchange_back);

		exchange_recevied = (TextView) view
				.findViewById(R.id.exchange_recevied_num);
		exchange_unrecevied = (TextView) view
				.findViewById(R.id.exchange_unrecevied_num);
		exhchange_pb_ll = (LinearLayout) view.findViewById(R.id.exchange_pb_ll);
		ll_not_pay = (LinearLayout) view.findViewById(R.id.ll_not_pay);
		ls_not_pay = (ListView) view.findViewById(R.id.not_pay_list);
		tv_not_pay_num = (TextView) view.findViewById(R.id.not_pay_num);
		hasExchangelistview = (ListView) view
				.findViewById(R.id.exchange_recevide_list);
		noExchangelistview = (ListView) view
				.findViewById(R.id.exchange_unrecevide_list);
		recevied_rl = (LinearLayout) view.findViewById(R.id.recevied_ll);
		unrecevied_rl = (LinearLayout) view.findViewById(R.id.unrecevied_ll);
		exchange_success_sv = (ScrollView) view
				.findViewById(R.id.exchange_success_sv);

		LayoutParams lp1 = recevied_rl.getLayoutParams();
		lp1.height = (int) (IConstants.DisplayWidth / 9.2);
		recevied_rl.setLayoutParams(lp1);
		unrecevied_rl.setLayoutParams(lp1);
		ll_not_pay.setLayoutParams(lp1);

		LayoutParams lp2 = exchange_recevied.getLayoutParams();
		float dex = (float) IConstants.DisplayWidth / 1280;
		lp2.height = (int) (80 * dex);
		lp2.width = (int) (140 * dex);
		exchange_recevied.setLayoutParams(lp2);
		exchange_unrecevied.setLayoutParams(lp2);
		tv_not_pay_num.setLayoutParams(lp2);
		exchangeListAction = new ExchangeListAction(su.getUserID(),
				su.getUserLoginToken());
		exchangeListModule = new ExchangeListModule();
		noExChangeList.clear();
		hasExChangeList.clear();
		notPayList.clear();
	}

	@Override
	public void setOnClick() {
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				FragmentManager fm = getFragmentManager();
				fm.popBackStack();

			}
		});

	}

	private void receiveDailog(final List<MyExchange> list, final int position) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle(getString(R.string.exchange_dialog_content));
		builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				receive(list, position);
			}
		});
		builder.setPositiveButton("取消", null);
		builder.create().show();

	}

	private void rePayForGoods(final List<MyExchange> list, final int position) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle(getString(R.string.repay_for_goods_dialog_title));
		builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				IConstants.download(getActivity(), list.get(position)
						.getPayUrl());

			}
		});
		builder.setPositiveButton("取消", null);
		builder.create().show();

	}

	private void receive(List<MyExchange> list, int position) {
		pd.show();
		exchange = list.get(position);
		receiveAction = new ReceiveAction(su.getUserID(),
				su.getUserLoginToken(), exchange.getType(),
				exchange.getExchangeCode());
		receiveModule = new ReceiveModule();
		receivePresistence = new ReceivePresistence(this);
		receivePresistence.setActitons(receiveAction);
		receivePresistence.setModule(receiveModule);
		receivePresistence.execute();
	}

	@Override
	public void showLoading() {
		dataLoadDialog.show();
		exchangeListPresistence = new ExchangeListPresistence(this);
		exchangeListPresistence.setActitons(exchangeListAction);
		exchangeListPresistence.setModule(exchangeListModule);
		exchangeListPresistence.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (exchangeListPresistence != null) {
					exchangeListPresistence.cancel(true);
				}
				getFragmentManager().popBackStack();

			}
		});
		dataLoadDialog.show();
	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			setExchangeList(exchangeListModule.list);
		} else {
			refresh(map);
		}
	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		pd.cancel();
		if (map.containsKey("0")) {
			if (receiveModule.isReceiveSuccess) {
				Toast.makeText(getActivity(), "领取成功", Toast.LENGTH_SHORT)
						.show();
				reSetList();
			}
		} else {
			Toast.makeText(getActivity(), "领取失败", Toast.LENGTH_SHORT).show();
		}

	}

	private void reSetList() {
		exchange.setState("1");
		hasExChangeList.add(exchange);
		noExChangeList.remove(exchange);
		exchange_recevied.setText(hasExChangeList.size() + "");
		exchange_unrecevied.setText(noExChangeList.size() + "");
		tv_not_pay_num.setText(notPayList.size() + "");
		hasAdapter.notifyDataSetChanged();
		noAdapter.notifyDataSetChanged();
		notPayAdapter.notifyDataSetChanged();
		IConstants.setListViewHeightBasedOnChildren(hasExchangelistview);
		IConstants.setListViewHeightBasedOnChildren(noExchangelistview);
		IConstants.setListViewHeightBasedOnChildren(ls_not_pay);

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	private void setExchangeList(List<MyExchange> list) {
		if (list == null || list.size() == 0) {
			return;
		}
		for (int i = 0; i < list.size(); i++) {
			String state = list.get(i).getState();
			String Type = list.get(i).getType();
			String Success = list.get(i).getSuccess();
			int mState = getState(Type, state, Success);
			if (mState == 1) {
				noExChangeList.add(list.get(i));
			} else if (mState == 2) {
				hasExChangeList.add(list.get(i));
			} else if (mState == 3) {
				notPayList.add(list.get(i));
			}

		}

		if (hasExChangeList.size() != 0) {
			exchange_recevied.setText(hasExChangeList.size() + "");
			setHasExChangeList();
		} else {
			exchange_recevied.setText("0");
			setHasExChangeList();
		}

		if (noExChangeList.size() != 0) {
			exchange_unrecevied.setText(noExChangeList.size() + "");
			setNoExChangeList();
		} else {
			exchange_unrecevied.setText("0");
		}
		if (notPayList.size() != 0) {
			tv_not_pay_num.setText(notPayList.size() + "");
			setNotPayList();
		} else {
			tv_not_pay_num.setText("0");
		}

		IConstants.setListViewHeightBasedOnChildren(hasExchangelistview);
		IConstants.setListViewHeightBasedOnChildren(noExchangelistview);
		IConstants.setListViewHeightBasedOnChildren(ls_not_pay);

	}

	protected void setNoExChangeList() {
		noAdapter = new ExChangeAdapter(getActivity(), noExChangeList);
		noExchangelistview.setAdapter(noAdapter);
		noExchangelistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				ORFragment orFragment = new ORFragment();
				Bundle b = new Bundle();
				b.putString("or",
						"{\"Type\":\""
								+ noExChangeList.get(position).getType()
								+ "\",\"Exchange_Code\":\""
								+ noExChangeList.get(position)
										.getExchangeCode() + "\"}");
				b.putString("name", noExChangeList.get(position).getProduct_Name());
				b.putString("code", noExChangeList.get(position).getExchangeCode());
				b.putString("time", noExChangeList.get(position).getExchange_Time());
				orFragment.setArguments(b);
				getFragmentManager().beginTransaction()
						.replace(R.id.fragment, orFragment)
						.addToBackStack(null).commit();

			}
		});

	}

	protected void setHasExChangeList() {
		hasAdapter = new ExChangeAdapter(getActivity(), hasExChangeList);
		hasExchangelistview.setAdapter(hasAdapter);
	}

	protected void setNotPayList() {
		notPayAdapter = new ExChangeAdapter(getActivity(), notPayList);
		ls_not_pay.setAdapter(notPayAdapter);
		ls_not_pay.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (notPayList.get(position).getPayUrl().equals("")) {
					Toast.makeText(getActivity(), "支付失败，不能再次支付",
							Toast.LENGTH_SHORT).show();
				} else {
					rePayForGoods(notPayList, position);
				}

			}
		});
	}

	class ExChangeAdapter extends BaseAdapter {
		LayoutInflater inflater;
		List<MyExchange> list;
		int mState = 0;

		public ExChangeAdapter(Context context, List<MyExchange> list) {
			inflater = LayoutInflater.from(context);
			this.list = list;

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			String type = list.get(position).getType();
			String state = list.get(position).getState();
			String Success = list.get(position).getSuccess();
			mState = getState(type, state, Success);
			ViewHolder viewHolder;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = inflater.inflate(R.layout.exchange_item, null);
				viewHolder.im = (ImageView) convertView
						.findViewById(R.id.series_item_image);

				viewHolder.name = (TextView) convertView
						.findViewById(R.id.name);
				viewHolder.time = (TextView) convertView
						.findViewById(R.id.exchange_shop_time);
				viewHolder.code = (TextView) convertView
						.findViewById(R.id.exchange_code);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			imageLoader.displayImage(list.get(position).getLogo(),
					viewHolder.im, options);
			viewHolder.name.setText(list.get(position).getProduct_Name());
			viewHolder.code.setText("兑换码: "
					+ list.get(position).getExchangeCode());
			viewHolder.time.setText("有效期："
					+ list.get(position).getExchange_Time());

			return convertView;
		}

		class ViewHolder {
			ImageView im;
			TextView name, time, code;
		}

	}

	// 判断list中每一项状态
	private int getState(String Type, String state, String Success) {
		if ((state.equals("0") && Type.equals("1"))
				|| (state.equals("0") && Type.equals("2"))
				|| (Type.equals("3") && Success.equals("1") && state
						.equals("0"))) {
			return 1;
		} else if ((Type.equals("1") && state.equals("1"))
				|| (Type.equals("2") && state.equals("1"))
				|| (Type.equals("3") && Success.equals("1") && state
						.equals("1"))) {
			return 2;
		} else if ((!Success.equals("1")) && Type.equals("3")) {
			return 3;
		}
		return 0;
	}

}
